package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {
    //不把定时服务写死，从配置文件去取
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
        /*System.out.println(shardingContext.getShardingParameter());
        System.out.println("任务调用");*/
    }

    private void doWork(String type) {
        //1.远程调用秒杀服务查询数据
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByType(Integer.parseInt(type));
        //result有三种情况：1.服务挂了走降级方法返回null。2.调用服务出现异常{code:50201,msg:xxx}，被统一异常处理到。
        // 3.正常返回{code:50201,msg:"操作成功",data:List<SeckillVO>}
        if (result!=null && !result.hasError()){
            //2.把查询数据放到redis中
            List<SeckillProductVo> seckillProductVoList = result.getData();
            for (SeckillProductVo seckillProductVo:seckillProductVoList){
                redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(type),
                        seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                // 库存放入redis中
                redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(type),
                        seckillProductVo.getId()+"",seckillProductVo.getStockCount() + "");
            }
            System.err.println("数据同步成功");
        }
    }
}
